package com.sjgtw.cloud.web.largeEquipment.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sjgtw.cloud.common.core.constant.CacheConstants;
import com.sjgtw.cloud.common.core.utils.DateUtils;
import com.sjgtw.cloud.common.core.utils.SecurityUtils;
import com.sjgtw.cloud.common.core.utils.StringUtils;
import com.sjgtw.cloud.common.core.web.domain.AjaxResult;
import com.sjgtw.cloud.common.redis.service.RedisService;
import com.sjgtw.cloud.service.SystemServerService;
import com.sjgtw.cloud.system.api.model.LoginUser;
import com.sjgtw.cloud.web.largeEquipment.domain.LargeEquipment;
import com.sjgtw.cloud.web.largeEquipment.mapper.LargeEquipmentMapper;
import com.sjgtw.cloud.web.largeEquipment.service.ILargeEquipmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * equipmentService业务层处理
 * 
 * @author ruoyi
 * @date 2024-03-09
 */
@Service
public class LargeEquipmentServiceImpl implements ILargeEquipmentService
{
    @Autowired
    private LargeEquipmentMapper largeEquipmentMapper;

    @Autowired
    private SystemServerService systemServerService;

    @Autowired
    private RedisService redisService;

    /**
     * 查询equipment
     * 
     * @param id equipment主键
     * @return equipment
     */
    @Override
    public LargeEquipment selectLargeEquipmentById(Long id)
    {
        return largeEquipmentMapper.selectLargeEquipmentById(id);
    }

    /**
     * 查询equipment列表
     * 
     * @param largeEquipment equipment
     * @return equipment
     */
    @Override
    public List<Map<String,Object>> selectLargeEquipmentList(LargeEquipment largeEquipment)
    {
        return largeEquipmentMapper.selectLargeEquipmentList(largeEquipment);
    }

    @Override
    public List<LargeEquipment> selectLargeEquipmentList2(LargeEquipment largeEquipment) {
        return largeEquipmentMapper.selectLargeEquipmentList2(largeEquipment);
    }

    /**
     * 新增equipment
     * 
     * @param largeEquipment equipment
     * @return 结果
     */
    @Override
    public int insertLargeEquipment(LargeEquipment largeEquipment)
    {
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        largeEquipment.setCreateBy(user.getUsername());
        largeEquipment.setCreateTime(new Date());
        return largeEquipmentMapper.insertLargeEquipment(largeEquipment);
    }

    /**
     * 修改equipment
     * 
     * @param largeEquipment equipment
     * @return 结果
     */
    @Override
    public int updateLargeEquipment(LargeEquipment largeEquipment)
    {
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        largeEquipment.setUpdateBy(user.getUsername());
        largeEquipment.setUpdateTime(new Date());
        return largeEquipmentMapper.updateLargeEquipment(largeEquipment);
    }

    /**
     * 批量删除equipment
     * 
     * @param ids 需要删除的equipment主键
     * @return 结果
     */
    @Override
    public int deleteLargeEquipmentByIds(Long[] ids)
    {
        return largeEquipmentMapper.deleteLargeEquipmentByIds(ids);
    }

    /**
     * 删除equipment信息
     * 
     * @param id equipment主键
     * @return 结果
     */
    @Override
    public int deleteLargeEquipmentById(Long id)
    {
        return largeEquipmentMapper.deleteLargeEquipmentById(id);
    }

    @Override
    public List<String> check(List<LargeEquipment> entities) {
        List<String> errors = new ArrayList<>();
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        List<String> deptNames = extractAndDeduplicateNames(entities);
        AjaxResult result = systemServerService.getDeptByNames(StringUtils.join(deptNames, ","));
        Map<String, Long> deptMap = new HashMap<>();
        if (result != null) {
            Object object = result.get("data");
            if (object != null) {
                JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(object));
                if (!jsonArray.isEmpty()) {
                    for (int i=0; i<jsonArray.size();i++) {
                        JSONObject json = jsonArray.getJSONObject(i);
                        deptMap.put(json.getString("deptName"), json.getLong("deptId"));
                    }
                }
            }
        }

        for (LargeEquipment entity : entities) {
            if (StringUtils.isNotEmpty(entity.getWorkArea())) {
                String[] split = entity.getWorkArea().split(",");
                if(split.length>0){
                    String depts = "";
                    for (int i = 0; i < split.length; i++) {
                        if (deptMap.containsKey(split[i])) {
                            depts += String.valueOf(deptMap.get(split[i])) +",";
                        }else{
                            errors.add("序号为" + entity.getNum() + "行数据工区:"+split[i]+"不存在");
                        }
                    }
                    entity.setWorkAreaId(depts.substring(0,depts.length()-1));
                }

            }
            if (user != null) {
                entity.setCreateBy(user.getUsername());
            }
            entity.setCreateTime(DateUtils.getNowDate());
        }
        return errors;
    }

    @Override
    public void batchSave(List<LargeEquipment> entities) {
        if (entities != null && entities.size() > 0) {
            if (entities.size() >= 200) {
                int index = 0;
                while (index <= entities.size()) {
                    int last = Math.min(index + 200, entities.size());
                    List<LargeEquipment> temp = entities.subList(index, last );
                    if (temp != null && temp.size() > 0) {
                        largeEquipmentMapper.batchSave(temp);
                    }
                    index += 200;
                }
            } else {
                largeEquipmentMapper.batchSave(entities);
            }
        }
    }

    private static List<String> extractAndDeduplicateNames(List<LargeEquipment> entities) {
        Set<String> uniqueNamesSet = new HashSet<>();

        for (LargeEquipment entity : entities) {
            String[] split = entity.getWorkArea().split(",");
            if(split.length>0){
                for (int i = 0; i < split.length; i++) {
                    uniqueNamesSet.add(split[i]);
                }
            }

        }

        return new ArrayList<>(uniqueNamesSet);
    }

}
